<?php

namespace app\common\model\renovation;

use app\common\model\BaseModel;

class CategoryModel extends BaseModel
{
    protected $table = 't_file_category';

    //删除校验关联关系表是否存在关联数据
    protected $checkDelJoinTable = [
        't_file|文件' => 'category_id=%s',
    ];

    /**
     * 删除分类
     * @param string $categoryIds
     * @return bool
     */
    public function delCategory($categoryIds)
    {
        $errorMsg = [];
        $this->startTrans();
        try {
            $categoryIds = explode(',', $categoryIds);
            $data = $this->whereIn('id', $categoryIds)->select()->column(null, 'id');
            foreach ($categoryIds as $k => $v) {
                $num = $k + 1;
                $info = $data[$v] ?? [];
                if (empty($info)) {
                    $errorMsg[] = "第{$num}个分类信息不存在或已删除";
                    continue;
                }

                $isExistSonCategory = $this->where('parent_id', $info['id'])->find();
                if ($isExistSonCategory) {
                    $errorMsg[] = "第{$num}个分类存在子分类，请先删除子分类";
                    continue;
                }

                if ($this->checkDelIsExistJoinData($info['id'])) {
                    $errorMsg[] = "第{$num}个分类" . $this->getError();
                }
            }

            if (empty($errorMsg)) {
                $this->whereIn('id', array_column($data, 'id'))->delete();
            }

            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            return $this->setError($e->getMessage());
        }

        if (!empty($errorMsg)) {
            return $this->setError($errorMsg);
        }

        return true;
    }

    /**
     * 根据分类ID获取所有下级分类ID集
     * @param int $categoryId 分类ID
     * @param int $depth 递归深度
     * @return array
     */
    public function getAllSonIds($categoryId, $depth = 0)
    {
        $categoryData = $this->where('parent_id', $categoryId)->field('id')->select()->toArray();
        $ids = array_column($categoryData, 'id');
        if ($ids) {
            foreach ($ids as $v) {
                $temp = $this->getAllSonIds($v, ++$depth);
                $ids = array_merge($ids, $temp);
            }
        }
        return $ids;
    }

}